//素金新增和编辑页面

var RATE=Number($.cookie("PrimeGoldRate"));
var EDITMODE=false;
(function(){
	var addForm={
		init:function(){
			myApp.showIndicator();
			this.bindEvents();
			this.loadCommon();
			myApp.hideIndicator();
		},
		bindEvents:function(){
			var self=this;
			$("#rate").text(RATE);
			//编辑
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				ID = args["ID"];//产品ID		
				EDITMODE=true;
			}
			if(EDITMODE){
				$(".category").hide();
				self.bindData(ID);
				$("#page_title").html("素金编辑");
			}else{
				$(".category").show();
				$("#page_title").html("素金新增");
			}
			//关闭弹框
			$("#close_tip_btn").on("click",function(){
				$("#tip_box").hide();
			});
			//提交验证
			$("#submit_btn").on("click",function(){
				$("#form_data").submit();
			});
			$("#reset_btn").on("click",function(){
				if(EDITMODE){
					myApp.alert("编辑时不能重置参数！");
				}else{
					$("#form_data")[0].reset();
				}				
			});
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                	self.addProduct();
                },
                rules: {
                    OriginSN: "required",
                    Count: "required",
                    UnitPrice: {
					    required: true,
					    max: 1000000000
					  },
                },
                messages: {
                    OriginSN: "",
                    Count: "",
                    UnitPrice: {
                    	required:"",
					    max: "价格必须小于9位数"
					}, 
                }
            });
			
		},
		//编辑时绑定数据
		bindData:function(ID){
		    myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=ID;
			if(EDITMODE){
				submitJson.IsMyStock=true;
			}
			$.ajax({
				url:'/Team/GetPrimeGold',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')')
					if(res.msgcode==true){
						var data=res.msginfo;
						$("#form_data").setForm(data);//绑数据
						$("#id_input").prop({"name":"ID","value":data.ID});//ID
						
						//图片的绑定
						if(data.Images!=""){
							imgs = data.Images.split("|");
							 for (var i=0; i< imgs.length;i++) {
							 	var img_boxHmtl=[
					    			'<section class="up-section fl load">',
										'<span class="up-span"></span>',
										'<img src="/images/a7.png" class="close-upimg">',
										'<img src=',imgs[i],' class="up-img" data-src=',imgs[i],'>',
										'<p class="img-namep"></p>',
										'<input id="taglocation" name="taglocation" value="" type="hidden">',
										'<input id="tags" name="tags" value="" type="hidden">',
									'</section>'
					    		].join('');
					    		$("#img_box").append(img_boxHmtl);
							 }
						}						
					}else{
						myApp.alert("加载失败！");
					}
					myApp.hideIndicator();//隐藏加载中
				}
			});
		},
		//新增提交
		addProduct:function(){
			//图片链接
			var images=[];
			var img_sectionLength=$(".img-section").find("section.up-section").length;
			if(img_sectionLength==0){
				myApp.alert("请上传图片");
			}else{
				myApp.showPreloader("上传中，请稍等!");
				//获取图片地址
				for(var i=0;i<img_sectionLength;i++){
					var img_li=$(".img-section").find("section.up-section").eq(i);
					var img_src=img_li.find(".up-img").attr("data-src");
					images.push(img_src);
				}
	    		var imgs=images.join('|');//拼成字符串
	    		$("#Images").val(imgs);//图片
	    		var $TotalWeight=$("#TotalWeight").val();//总重
	    		var $PurchaseLaborCost=$("#PurchaseLaborCost").val();//买入工费
	    		var $PurchaseGoldPrice=$("#PurchaseGoldPrice").val();//买入金价
	    		var $PurchaseCostPrice=$("#PurchaseCostPrice").val();//成本价
	    		if($TotalWeight==""){
	    			$("#TotalWeight").removeAttr("name");
	    		}
	    		if($PurchaseLaborCost==""){
	    			$("#PurchaseLaborCost").removeAttr("name");
	    		}
	    		if($PurchaseGoldPrice==""){
	    			$("#PurchaseGoldPrice").removeAttr("name");
	    		}
	    		if($PurchaseCostPrice==""){
	    			$("#PurchaseCostPrice").removeAttr("name");
	    		}
			    var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
		             result[item.name] = item.value;
		            return result;
		        }, {})//把提交的数据转为JSON格式
		        if(EDITMODE){
		        	var manageURL="/team/ModPrimeGolds";
		        }else{
		        	var manageURL="/team/AddPrimeGolds";
		        }
				 $.ajax({
				 	type:"POST",
				 	url:manageURL,
				 	data:JSON.stringify(finalRes),
				 	contentType: "application/json; charset=utf-8",
	                success: function (result) {
	                	var _result = eval('(' + result + ')');//eval()解析单个json对象
	                	myApp.hidePreloader();
	                	if(EDITMODE){
	                		var tipString="修改";
	                	}else{
	                		var tipString="新增";
	                	}
	                	if(_result.result==true){
	                		myApp.alert(tipString+"成功！");
	                	}else{
	                		myApp.alert(tipString+"失败！");
	                	}
	                }
				 });
			}
			
		},
		
		//公共参数
		loadCommon:function(){
			var self=this;

			//品类
			var $Type='';
			for(var i=0;i<prime_gold[1].Type.length;i++){
				$Type+='<option value="'+prime_gold[1].Type[i][0]+'">'+prime_gold[1].Type[i][1]+'</option>';
			}
			$("#data_Type").html($Type);	
			//工艺造型
			var $Style='';
			for(var i=0;i<prime_gold[1].Style.length;i++){
				$Style+='<option value="'+prime_gold[1].Style[i][0]+'">'+prime_gold[1].Style[i][1]+'</option>';
			}
			$("#data_Style").html($Style);
			//约重
			var $Weight='';
			for(var i=0;i<prime_gold[1].Weight.length;i++){
				$Weight+='<option value="'+prime_gold[1].Weight[i][0]+'">'+prime_gold[1].Weight[i][1]+'</option>';
			}
			$("#data_Weight").html($Weight);
			//材质
			var $Material='';
			for(var i=0;i<prime_gold[1].Material.length;i++){
				$Material+='<option value="'+prime_gold[1].Material[i][0]+'">'+prime_gold[1].Material[i][1]+'</option>';
			}
			$("#data_Material").html($Material);
			//是否现货
			var $IsStock='';
			for(var i=0;i<prime_gold[1].IsStock.length;i++){
				$IsStock+='<option value="'+prime_gold[1].IsStock[i][0]+'">'+prime_gold[1].IsStock[i][1]+'</option>';
			}
			$("#data_IsStock").html($IsStock);		
		},

	}
	addForm.init();
})();
